package voxietest1.jam;

import processing.core.PApplet;
import voxietest1.ParticleSystem;
import voxietest1.VoxiObject;

public class Ball extends VoxiObject {
	public float x;
	public float y;
	public float z;
	public float radius;
	
	public float vx = 0;
	public float vy = 0;
	public float vz = 0;
	public ParticleSystem ps = new ParticleSystem(3.0f);
	public World world;
	public int nbounces = 0;
	
	public float startdelay = 2.0f;
	
	public Ball(World w, float xx, float yy, float zz) {
		x = xx;
		y = yy;
		z = zz;
		world = w;
		radius = .1f;
	}
	
	
	public void RestartBall() {
		x = 0;
		y = 0;
		z = world.zmin;
		vz = 0;
		startdelay = 2.0f;
		float a = pApplet.random(0f, (float)(2*Math.PI));
		vx = .8f*pApplet.sin(a);
		vy = .8f*pApplet.cos(a);
	}
	
	public void myUpdate() {
		float deltaTime = (float)scene.deltaTime;
		boolean isCollision = false;
		
		if (startdelay >= 0 && startdelay-deltaTime <= 0) {
			// crossing the start - reset nbounces
			nbounces = 0;
		}
		
		startdelay -= deltaTime;
		
		if (startdelay > 0) {
			// wait for delay to start game
		} else {
			x += vx*deltaTime;
			y += vy*deltaTime;
			z += vz*deltaTime;
		
			vz += deltaTime*.8;
				
				
			if (z < world.zmin) {
				z = world.zmin;
				vz = -vz;
				isCollision = true;
				
			}
			
			if (z > world.zmax) {
				z = world.zmax;
				vz = -vz;
				isCollision = true;
				
				if (!world.paddle.isInPaddle(x, y)) {
					// missed paddle
					ps.MakeBurst(0, 1, 2, 500);
					RestartBall();
					world.paddle.resetSize();
				} else {
					// hit paddle
					world.paddle.shrinkSize();
					nbounces += 1;
	
				}
			}
			
			if (x-radius < world.xmin) {
				x = world.xmin+radius;
				vx = -vx;
				isCollision = true;
			}
			if (x+radius > world.xmax) {
				x = world.xmax-radius;
				vx = -vx;
				isCollision = true;
			}
			if (y-radius < world.ymin) {
				y = world.ymin+radius;
				vy = -vy;
				isCollision = true;
			}
			if (y+radius > world.ymax) {
				y = world.ymax-radius;
				vy = -vy;
				isCollision = true;
			}
		}
		
		ps.setEmitterPosition(x,y,z);
		if (isCollision) {
			ps.MakeBurst(0.5f, 1.3f, .75f, 400);
		}
		ps.myUpdate();
	}

	@Override
	public void mySetup() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void myDraw() {
		// TODO Auto-generated method stub
		ps.myDraw();
		voxi.voxi_drawsph(scene.frame,  x,  y,  z,  radius,  radius,  7);
		
	}
}
